package com.panopset.sf;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPasswordField;

import com.panopset.Numbers;
import com.panopset.op.Prompter;

/**
 * Swing prompter.
 * @author Karl Dinwiddie
 *
 */
public final class PrompterSwing extends Prompter {

    /**
     * @param args Not used.
     */
    public static void main(final String... args) {
        System.out.println(new PrompterSwing("Enter something").get());
    }

    /**
     * @param userPrompt User prompt.
     */
    public PrompterSwing(final String userPrompt) {
        super(userPrompt);
    }

    @Override
    public String get() {
        final JDialog d = StatusIndicator.createBarModalDialog();
        final JPasswordField tf = new JPasswordField(20);
        final JButton okayBtn = new JButton("OK");
        okayBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(final ActionEvent e) {
                d.dispose();
            }

        });
        JLabel lbl = new JLabel(getPrompt());
        lbl.setForeground(Color.YELLOW);
        d.add(lbl);
        d.add(tf);
        d.add(okayBtn);
        d.setAlwaysOnTop(true);
        d.getRootPane().setDefaultButton(okayBtn);
        d.setVisible(true);

        while (d.isVisible()) {
            try {
                Thread.sleep(Numbers.Integers.QUARTER_SECOND.getValue());
            } catch (InterruptedException e) {
                continue;
            }
        }
        return new String(tf.getPassword());
    }
}
